<template>
	<div>
		<div class="list-box" style="min-height:500px;">
			<div class="pannel-title pannel-between">
				<div>{{ title }}</div>
			</div>
			<div class="line"></div>
			<div class="data-table article-content" v-if="pageLoading && formState.isDel === 'Y'">
				<div class="is_del">已删除</div>
				<h2>{{formState.title}}</h2>
				<div class="article-info">
					<span>作者：{{formState.author}}</span>
					<span>分类：{{cateName}}</span>
					<span>创建时间：{{formState.createTime}}</span>
				</div>
				<mavon-editor ref="editor2" :externalLink="externalLink" codeStyle="dark" :ishljs="true" :subfield="false" defaultOpen="preview" :editable="false" style="height:100%" v-model="formState.content"></mavon-editor>
				<a-button type="default" shape="round" @click="cancel()">返回</a-button>
			</div>
			<div class="data-table" v-else-if="pageLoading && (!formState.isDel || formState.isDel === 'N')">
				<div class="pannel-form">
					<a-form ref="form1" :model="formState" :rules="rules" :labelCol="{ span: 3, offset: 0 }" :wrapperCol="{ span: 9, offset: 0 }">
						<a-form-item label="标题" name="title">
							<a-input v-model:value="formState.title" placeholder="请输入标题" />
						</a-form-item>
						<a-form-item label="作者" name="author">
							<a-input v-model:value="formState.author" placeholder="请输入作者姓名" />
						</a-form-item>
						<a-form-item label="正文" name="content" :wrapperCol="{ span: 21, offset: 0 }">
							<div style="height:500px;">
								<mavon-editor @imgAdd="$imgAdd" ref="editor" codeStyle="dark" :ishljs="true" style="height:100%" :externalLink="externalLink" v-model="formState.content"></mavon-editor>
							</div>
						</a-form-item>
						<a-form-item v-if="formState.id" label="预览正文">
							<a-button @click="showHtm">预览</a-button>
						</a-form-item>
						<a-form-item label="文章预览图" name="thumbnails">
							<avatar-upload width="200px" height="120px" v-model:value="formState.thumbnails"></avatar-upload>
							<a @click="showPicModal()">使用历史图片</a>
						</a-form-item>
						<a-form-item label="排序序号" name="displayPriority">
							<a-input v-model:value="formState.displayPriority" placeholder="请输入大于等于0的正整数">
								<template #suffix>
									<a-tooltip title="排序序号数值越小越靠前">
										<info-circle-outlined style="color: rgba(255, 0, 0, 0.7)" />
									</a-tooltip>
								</template>
							</a-input>
						</a-form-item>
						<a-form-item label="文章关键字" name="keywords">
							<tag-input maxCount="5" placeholder="请输入关键字，回车确认,最多输入5个" v-model:value="formState.keywords"></tag-input>
						</a-form-item>
						<a-form-item label="阅览权限" name="isMember">
							<a-radio-group name="radioGroup" v-model:value="formState.isMember">
								<a-radio value="Y">会员可阅览</a-radio>
								<a-radio value="N">不限制</a-radio>
							</a-radio-group>
						</a-form-item>
						<a-form-item label="是否隐藏" name="isHide">
							<a-select v-model:value="formState.isHide" :options="isHides" placeholder="请选择状态"></a-select>
						</a-form-item>
						<a-form-item label="分类" name="cateId">
							<!-- <a-tree-select v-model:value="formState.cateId" :replaceFields="{ children: 'children', title: 'name', key: 'id', value: 'id' }" :tree-data="cateIds" placeholder="请选择状态"></a-tree-select> -->
							<a-select v-model:value="formState.cateId">
								<a-select-opt-group v-for="item in cateIds" :key="item.id" :label="item.name">
									<a-select-option v-for="child in item.children" :key="child.id" :value="child.id">{{child.name}}</a-select-option>
								</a-select-opt-group>
							</a-select>
						</a-form-item>
						<a-form-item label="是否允许转载" name="allowReprint">
							<a-select v-model:value="formState.allowReprint" :options="allowReprints" placeholder="请选择状态"></a-select>
						</a-form-item>
						<!-- <a-form-item label="logo" name="logo">
							<avatar-upload v-model:value="formState.logo"></avatar-upload>
						</a-form-item> -->
					</a-form>
					<a-modal zIndex="1600" width="1000px" title="历史图片" v-model:visible="visiblePic" :maskClosable="false" :footer="null" :afterClose="closePicModal">
                        <a-table :columns="columnsPic" :row-key="(record) => record.id" :scroll="{ x: 800, y: 400 }" :data-source="dataSourcePic" :pagination="pagesPic" :loading="picLoading" @change="changePagePic">
                            <template #thumbnails="{ text }">
                                <img style="width:160px;height:96px;border-radius:4px;" :src="text" />
                            </template>
                            <template #action="{ record }">
                                <a @click="selectPic(record.thumbnails)">使用图片</a>
                            </template>
                        </a-table>
                    </a-modal>
				</div>
				<div class="pannel-form-btn">
					<a-button type="default" shape="round" @click="cancel()">返回</a-button>
					<a-button v-if="showSubmin" :loading="btnLoading" type="primary" shape="round" @click="confirm()">提交</a-button>
				</div>
			</div>
		</div>
		<div class="list-box" style="margin-top: 5px" v-if="isShowCommentList">
			<div class="pannel-title pannel-between">
				<div>评价</div>
			</div>
			<!-- 評價列表 -->
			<div class="data-table">
				<a-table :columns="columns" :row-key="(record) => record.id" :data-source="commentList" :pagination="false" :loading="isLoading">
					<template #action="{ record }">
						<a @click="deleteMenu(record)" title="删除"><img src="@/assets/images/cz-delete.png" /></a>
					</template>
					<template #time="{ text }">
						{{ formatDate(text) }}
					</template>
				</a-table>
			</div>
		</div>
		<!-- 遮罩弹框 -->
		<div class="htm" v-if="isShowHtm">
			<div class="title">
				<p>
					{{ formState.title }}
					<span @click="closeHtm">
						<svg viewBox="64 64 896 896" data-icon="close" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class="">
							<path
								d="M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z"
							></path>
						</svg>
					</span>
				</p>
			</div>
			<div class="htm-body" v-html="formState.content"></div>
		</div>
	</div>
</template>
<script>
import { InfoCircleOutlined } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { ref,reactive } from "@vue/reactivity";
import { message, Button, Form, Input, Tooltip, Select, Table, Modal, Radio } from "ant-design-vue";
import httpRequest from "@/util/httpRequest";
import baseUtil from "@/util/baseUtil";
import tagInput from "@/components/tagInput";
import avatarUpload from "@/components/avatarUpload";
import {mavonEditor} from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
export default {
	components: {
		InfoCircleOutlined,
		ATable: Table,
		AButton: Button,
		AForm: Form,
		AFormItem: Form.Item,
		AModal:Modal,
		AInput: Input,
		ATooltip: Tooltip,
		ASelect: Select,
		ASelectOptGroup:Select.OptGroup,
		ASelectOption:Select.Option,
		ARadio:Radio,
		ARadioGroup:Radio.Group,
		tagInput,
		avatarUpload,
		mavonEditor
	},
	setup() {
		const store = useStore();
		//text：页面头部面包屑的显示文字，isBack：是否显示页面头部返回按钮
		store.dispatch("setBreadcrumb", {
			text: "文章管理 / 漏洞文章",
			isBack: true,
		});
		const formState = ref({
			id: null,
			title: "",
			author: "",
			displayPriority: "",
			cateId: "",
			// logo: "",
			content: "",
			allowReprint: "",
			isHide: "",
			isMember:"",
			keywords:"",
			editType:"MD",
			thumbnails:""
		});
		const allowReprints = ref([
			{ value: "Y", label: "允许" },
			{ value: "N", label: "不允许" },
		]);
		const isHides = ref([
			{ value: "Y", label: "隐藏" },
			{ value: "N", label: "显示" },
		]);
		const externalLink = true;
		// const externalLink = ref({
        //     markdown_css: function() {
        //         return process.env.VUE_APP_BASEPATH+'/markdown/github-markdown.min.css';
        //     },
        //     hljs_js: function() {
        //         return process.env.VUE_APP_BASEPATH+'/highlightjs/highlight.min.js';
        //     },
        //     hljs_css: function(css) {
        //         return process.env.VUE_APP_BASEPATH+'/highlightjs/styles/' + css + '.min.css';
        //     },
        //     hljs_lang: function(lang) {
        //         return process.env.VUE_APP_BASEPATH+'/highlightjs/languages/' + lang + '.min.js';
        //     },
        //     katex_css: function() {
        //         return process.env.VUE_APP_BASEPATH+'/katex/katex.min.css';
        //     },
        //     katex_js: function() {
        //         return process.env.VUE_APP_BASEPATH+'/katex/katex.min.js';
        //     },
        // });
		const dataSourcePic = ref([]);
		const columnsPic = reactive([
			{
				title: "文章标题",
				dataIndex: "title",
				key: "title",
			},
			{
				title: "预览图",
				dataIndex: "thumbnails",
				key: "thumbnails",
                width:240,
				slots: { customRender: "thumbnails" },
			},
			{
				title: "操作",
				key: "action",
                width:100,
				slots: { customRender: "action" },
			},
		]);
		const pagesPic = ref({
			keywords: "",
			cateId1: 0,
			cateId2: 0,
			status: "",
			current: 1,
			pageSize: 10,
			total:0
		});
		return {
			formState,
			btnLoading: ref(false),
			pageLoading: ref(true),
			cateIds: ref([]),
			cateList: ref([]),
			allowReprints,
			isHides,
			isLoading:ref(false),
			toolbarsExclude:ref(['revoke','next', 'save','htmlPreview','github']),
			externalLink,
			dataSourcePic,
            columnsPic,
            pagesPic,
            picLoading:ref(false),
			visiblePic:ref(false),
		};
	},
	data() {
		return {
			rules: {
				author: {
					required: true,
					message: "作者名称不能为空",
					trigger: "blur",
				},
				cateId: {
					required: true,
					message: "不能为空",
					trigger: "change",
					type: "number",
				},
				title: {
					required: true,
					message: "文章标题不能为空",
					trigger: "blur",
				},
				content: [
					{
						required: true,
						message: "文章内容不能为空",
						trigger: "blur",
					},
				],
				allowReprint: {
					required: true,
					message: "不能为空",
					trigger: "blur",
				},
				isHide: {
					required: true,
					message: "不能为空",
					trigger: "blur",
				},
				isMember: {
					required: true,
					message: "不能为空",
					trigger: "change",
				},
				displayPriority: [
					{
						required: true,
						message: "不能为空",
						trigger: "blur",
					},
					{
						trigger: "blur",
						message: "请输入大于等于0的整数",
						pattern: /^(0|[1-9]\d*)$/,
					},
				],
			},
			title: "新增漏洞文章",
			showSubmin: true,
			isShowCommentList: false,
			commentList: [],
			pages: {
				page: 1,
				pageSize: 10,
			},
			columns: [
				{
					title: "编号",
					dataIndex: "id",
					key: "id",
				},
				{
					title: "用户ID",
					dataIndex: "name",
					key: "name",
				},
				{
					title: "内容",
					dataIndex: "comment",
					key: "comment",
				},
				{
					title: "发布时间",
					dataIndex: "create_time",
					key: "create_time",
					slots: { customRender: "time" },
				},
				{
					title: "操作",
					key: "action",
					slots: { customRender: "action" },
				},
			],
			isShowHtm: false,
		};
	},
	computed:{
		cateName(){
			let text = "";
			if(this.cateList && this.formState && this.formState.cateId){
				const cate = this.cateList.filter(e=>e.id === this.formState.cateId);
				if(cate &&cate.length>0){
					text = cate[0].name;
				}
			}
			return text;
		}
	},
	mounted() {
		if (this.$route.query.id) {
			this.isShowCommentList = true;
			this.title = "編輯漏洞文章";
			this.pageLoading = false;
			httpRequest.post("获取漏洞文章详情", { id: this.$route.query.id }).then((res) => {
				this.formState = { ...baseUtil.LineToHump(res.data) };
				this.formState.keywords = this.formState.keywords.join(",");
				this.formState.displayPriority = String(this.formState.displayPriority);
				this.formState.createTime = baseUtil.DateFormat(this.formState.createTime*1000,"yyyy-MM-dd HH:mm:ss");
				if (this.formState.isDel == "Y") {
					this.showSubmin = false;
				}
			}).finally(()=>{this.pageLoading = true;});
			this.pages.articleId = this.$route.query.id;
			httpRequest.post("获取漏洞文章评论列表", this.pages).then((res) => {
				this.commentList = res.data.data;
			});
		}else{
			this.formState.displayPriority = sessionStorage.getItem('displayPriority');
		}
		httpRequest.post("获取文章分类集合", { level: "1", type: "Vuln" }).then((res) => {
			this.cateList = res.data;
			this.cateIds = baseUtil.GetByTree(res.data);
		});
	},
	methods: {
		confirm() {
			this.$refs.form1.validate().then(() => {
				this.btnLoading = true;
				const url = this.formState.id ? "编辑漏洞文章" : "创建漏洞文章";
				const msg = this.formState.id ? "修改成功" : "创建成功";
				if (!this.formState.id) {
					delete this.formState.id;
				}
				httpRequest
					.post(url, this.formState)
					.then(() => {
						this.visible = false;
						this.$router.push("/bugArticle");
						message.success(msg);
					})
					.finally(() => {
						this.btnLoading = false;
					});
			});
		},
		cancel() {
			this.$router.back();
		},
		closePicModal(){
            this.visiblePic = false;
        },
        changePagePic(e){
            this.pagesPic.current = e.current;
			this.getList();
        },
        showPicModal(){
            this.pagesPic.current = 1;
            this.getList();
            this.visiblePic = true;
        },
        selectPic(imgUrl){
            this.formState.thumbnails = imgUrl;
            this.visiblePic = false;
        },
        getList() {
			this.picLoading = true;
			httpRequest
				.post("获取漏洞文章列表",{...this.pagesPic,page:this.pagesPic.current})
				.then((res) => {
					this.dataSourcePic = res.data.data;
					this.pagesPic.total = res.data.total;
				})
				.finally(() => {
					this.picLoading = false;
				});
		},
		deleteMenu(item) {
			Modal.confirm({
				title: "系统提示",
				content: "确认删除此评论？",
				okText: "删除",
				cancelText: "取消",
				onOk: () => {
					return new Promise((res) => {
						this.isLoading = true;
						httpRequest
							.post("删除漏洞文章评论", { id: item.id })
							.then(() => {
								message.success("成功删除评论！");
								httpRequest.post("获取漏洞文章评论列表", this.pages).then((res) => {
									this.commentList = res.data.data;
								});
							})
							.catch(() => {
								message.warning({ content: "删除评论失败", key: "error" });
							})
							.finally(() => {
								this.isLoading = false;
								res();
							});
					});
				},
			});
		},
		formatDate(val) {
			return baseUtil.getTime(val);
		},
		onEditorChange(editor) {
			this.formState.content = editor.html;
		},
		showHtm() {
			this.isShowHtm = true;
		},
		closeHtm() {
			this.isShowHtm = false;
		},
		$imgAdd(pos, $file){
			httpRequest.uploadFileByFormData($file).then(res=>{
				this.$refs.editor.$img2Url(pos,res.data.fileUrl);
			})
		}
	},
};
</script>
<style lang="less" scoped>
.pannel-form{
	width: 100%;
}
.line {
	width: 100%;
	margin: 20px 0;
	border-top: 1px solid #eee;
}
.article-content{
	position: relative;
	h2{
		font-size: 26px;
		height: 60px;
		line-height: 60px;
	}
	.article-info{
		background: #fafafa;
		color: #888;
		padding:10px;
		border-radius: 5px;
		margin-bottom: 30px;
		span{
			margin:0 20px;
		}
	}
	.content{
		margin-bottom: 30px;
	}
	.is_del{
		width: 100px;
		height: 100px;
		border:3px solid rgba(255,0,0,0.2);
		border-radius:50px;
		font-size: 24px;
		text-align: center;
		line-height: 100px;
		color: rgba(255,0,0,0.3);
		transform: rotate(-30deg);
		position: absolute;
		right: 0;
		top: 0;
	}
}
</style>
